using System.Net;
using System.Net.Sockets;
using System.Text;

namespace _2024_8_4_实现udp客户端_群聊室_
{
    public partial class Form1 : Form
    {
        delegate void SetFormTextDelegate(String str);
        SetFormTextDelegate SetFormText;
        Socket socket;
        bool isUDP = true;
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 客户端给服务端发消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Send_Button_Click(object sender, EventArgs e)
        {
            byte[] sendDate = System.Text.Encoding.UTF8.GetBytes(InputWindow_TextBox.Text);
            InputWindow_TextBox.Text=string.Empty;
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(IP_TextBox.Text), int.Parse(Port_TextBox.Text));
            int n = 0;
            try
            {
                n = socket.SendTo(sendDate, endpoint);
            }
            catch (Exception s)
            {
                ShowMessage(s.Message);
            }

            if (n <= 0)
            {
                ShowMessage("发送失败");
            }




        }

        private void InputWindow_TextBox_TextChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 初始化一些变量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            InputWindow_TextBox.Text = string.Empty;
            ChatWindow_TextBox.Text = string.Empty;
            IP_TextBox.Text = "124.222.68.240";
            Port_TextBox.Text = "8080";
            this.SetFormText = ShowMessage;

            //thread_recive_message.Join();


        }



        private void Connect_Button_Click(object sender, EventArgs e)
        {
            isUDP = isUDP_CheckBox.Checked;
            if (isUDP)
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            }
            else
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            EndPoint server = new IPEndPoint(IPAddress.Parse(IP_TextBox.Text), int.Parse(Port_TextBox.Text));
            socket.Connect(server);
            Thread thread_recive_message = new Thread(new ThreadStart(ReciveServerMesage));
            thread_recive_message.IsBackground = true;
            thread_recive_message.Start();
            isUDP_CheckBox.Enabled = false;
            Connect_Button.Enabled = false;



        }

        void ShowMessage(string message)
        {
            ChatWindow_TextBox.AppendText(message + "\r\n");
        }

        void ReciveServerMesage()
        {
            byte[] date = new byte[1024 * 1024 * 3];
            EndPoint endPoint;
            int n = 0;
            while (true)
            {
                if (isUDP)
                {
                    endPoint = new IPEndPoint(IPAddress.Any, 0);
                    n = socket.ReceiveFrom(date, ref endPoint);
                    if (n < +0)
                    {
                        continue;
                    }
                }
                else
                {
                    if (socket.Connected)
                    {
                        try
                        {
                            n = socket.Receive(date);

                        }
                        catch (Exception)
                        {

                        }
                       
                    }

                }
                string s = Encoding.UTF8.GetString(date, 0, n);
                if (this != null)
                {
                    this.Invoke(SetFormText, new object[] { s });
                }


            }

        }

        private void InputWindow_TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Send_Button_Click(sender, e);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            System.Environment.Exit(0);
        }
    }
}
